/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package by.vdl.websort.controllers;

import by.vdl.websort.controllers.webForm.RegisterForm;
import by.vdl.websort.server.entity.CategoryDTO;
import by.vdl.websort.server.entity.StudyDTO;
import by.vdl.websort.server.entity.UserDTO;
import by.vdl.websort.server.entity.UserPassedStudyDTO;
import by.vdl.websort.server.entity.contextmodels.StudyModel;
import by.vdl.websort.server.entity.contextmodels.StudyUnsortedModel;
import by.vdl.websort.server.entity.datatransfer.StudyAndUserModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 *
 * @author zeor
 */
@Controller
@RequestMapping(value = {"/", "/index"})
//@SessionAttributes({"isAuth","userDTO"})
public class IndexController extends AbstractController{
    @RequestMapping(method = RequestMethod.GET)
    protected String getIndexPage(HttpSession session) throws Exception {
        //Boolean isAuth = (Boolean)session.getAttribute("isAuth");
        //if(isAuth!=null && isAuth)
            return "indexPage";
        //return "redirect:/auth/notLogged";
    }

    @RequestMapping(value="/service", method = RequestMethod.GET)
    protected String getServicePage(HttpSession session) throws Exception {
        Boolean isAuth = (Boolean)session.getAttribute("isAuth");
        if(isAuth!=null && isAuth)
            return "indexPage";
        return "redirect:/auth/notLogged";
    }
    
    @RequestMapping(value="/listUser", method = RequestMethod.GET)
    protected String listUser() throws Exception {
        List<UserDTO> userList = getCommonDao().getUserDao().getUsersList();
        for(UserDTO u: userList){
            System.out.println(u.getName()+" "+u.getHash());
        }
        return "redirect:/index";
    }
    
    @RequestMapping(value="/registerUser1", method = RequestMethod.POST)
    protected String registrUser(@ModelAttribute RegisterForm registerForm) throws Exception {
        System.out.println("name="+registerForm.getUserName());
        UserDTO userDTO = new UserDTO();
        userDTO.setName(registerForm.getUserName());
        userDTO.setPassword(registerForm.getUserPassword());
        userDTO.setIp("127000000001");
        getCommonDao().getUserDao().create(userDTO);
        return "redirect:/auth/notLogged";
    }
    @RequestMapping(value="/addStudy", method = RequestMethod.POST)
    @ResponseBody
    protected String addStudy(@RequestBody StudyModel studyModel, HttpSession session) throws Exception {
        UserDTO user = (UserDTO)session.getAttribute("userDTO");
        long studyId = getCommonDao().getStudyDao().addStudy(studyModel.getStudy(), user.getId());
        System.out.println("studyId="+studyId);
        List<String> catalogs = studyModel.getCategories();
        for(String cat: catalogs){
            getCommonDao().getStudyDao().addCategory(cat, studyId);
        }
        List<String> items = studyModel.getItems();
        for(String item: items){
            getCommonDao().getStudyDao().addItem(item, studyId);
        }
        return "ok";
    }
    
    @RequestMapping(value="/addCommpletedStudy", method = RequestMethod.POST)
    @ResponseBody
    protected String addCommpletedStudy(@RequestBody List<LinkedHashMap<String,Object>> studyCompletedModels, HttpSession session, HttpServletRequest request) throws Exception {
        System.out.println("studyCompletedModels: "+studyCompletedModels.size());
         String ipAddress = request.getHeader("X-FORWARDED-FOR");  
         ipAddress = (ipAddress != null)? ipAddress : request.getRemoteAddr();  
         System.out.println("ipAddress="+ipAddress);
         
         if(studyCompletedModels.size()>0){  
             LinkedHashMap<String,Object> fm = (LinkedHashMap<String,Object>)studyCompletedModels.get(0);
             Long categoryId = Long.valueOf((String)fm.get("categoryName"));
             CategoryDTO categoryDTO = getCommonDao().getStudyDao().getCategoryById(categoryId);
             System.out.println("categoryId="+categoryDTO.getId());
             UserPassedStudyDTO upsdto = getCommonDao().getUserDao().addUserPassedStudy(ipAddress, categoryDTO.getStudyId());
             for(LinkedHashMap<String,Object> lhm: studyCompletedModels){
                 Long cId = Long.valueOf((String)lhm.get("categoryName"));
                 List<String> ls = (List<String>)lhm.get("categoryItems");
                 for(String item: ls){
                     Long itm = Long.valueOf(item);
                    getCommonDao().getStudyDao().addSortedTable(cId, itm, upsdto.getId());
                 }
             }
         }
         
        return "ok";
    }
    
    @RequestMapping(value="/register", method = RequestMethod.GET)
    protected String registr() throws Exception {
        return "registerPage";
    }
    
    @RequestMapping(value="/sort")
    protected String sortStudy(@RequestParam long studyId, HttpSession session, ModelMap map) throws Exception {
        //todo add security to get study by hash
        System.out.println("studyId="+studyId);
        StudyUnsortedModel studyUnsortedModel = getCommonDao().getStudyDao().getUncompletedStudy(studyId);
        
        String categorySelector ="";         
        for(CategoryDTO category: studyUnsortedModel.getCategories())
            categorySelector = categorySelector + "#divCategory"+category.getId()+", ";
        
        map.put("categorySelector", categorySelector);
        map.put("unsortedStudy", studyUnsortedModel);
        
        return "sortPage";
    }
    
    
    @RequestMapping(value="/listStudy", method = RequestMethod.GET)
    protected String listStudy(ModelMap map) throws Exception {
        List<StudyDTO> studyList = getCommonDao().getStudyDao().listStudy();
        List<StudyAndUserModel> lsaum = new ArrayList<StudyAndUserModel>();
        for(StudyDTO studyDTO: studyList){
            UserDTO userDTO = getCommonDao().getUserDao().getUserById(studyDTO.getUserId());
            lsaum.add(new StudyAndUserModel(studyDTO, userDTO));
        }
        map.put("listStudy", lsaum);
        return "studyListPage";
    }

    @RequestMapping(value="/headTemplate", method = RequestMethod.GET)
    protected String headTeplate(ModelMap map) throws Exception {
        return "template/head";
    }

    @RequestMapping(value="/footTemplate", method = RequestMethod.GET)
    protected String footTemplate(ModelMap map) throws Exception {
        return "template/foot";
    }
}
